import jdk.internal.util.xml.impl.Input;

import java.io.*;
import java.util.Scanner;

public class Demo14 {
	/**
	 * 文件内容和名字中查找指定字符
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		//扫描指定目录，并找到名称或者是内容中含有指定字符的所有的普通文件(不包含目录)
		Scanner scanner=new Scanner(System.in);
		System.out.println("输入要扫描的目录：");
		String directory= scanner.next();
		File file=new File(directory);
		if(file.isFile()) {
			System.out.println("输入的是一个文件，输入有误");
			return ;
		}
		if(!file.exists() ) {
			System.out.println("输入的目录不存在，输入有误");
			return ;
		}
		System.out.println("请输入指定字符");
		String word=scanner.next();
		//System.out.println(file.getAbsolutePath());
		scanDir1(file,word);
	}

	public  static void scanDir1(File file, String word) throws IOException {
		File[] files = file.listFiles();
		if (files == null||files.length==0)return;
		for (File file1 : files) {
			if(file1.isDirectory()) {
				scanDir1(file1,word);
			}
			//这里逻辑出错了，如果是目录就继续扫描
			//不是目录就要判断内容中是不是有指定的字符
			else {
				if(checkWord(file1,word)) {
					System.out.println("文件内容中含有的指定字符" +file1.getAbsolutePath());
				} else {
					String fileName=file1.getName();
					if(fileName.contains(word)) {
						System.out.println("文件名字也含有指定字符："+file1.getAbsolutePath());
					}
				}
			}
		}
	}
	private static boolean checkWord(File file, String word) throws IOException {
		StringBuilder stringBuilder=new StringBuilder();
		try(InputStream inputStream=new FileInputStream(file)) {
			try(Scanner scanner=new Scanner(inputStream)) {
				while(scanner.hasNextLine()) {
					stringBuilder.append(scanner.nextLine());
					stringBuilder.append("\r\n");
				}
			}
		}
		return stringBuilder.indexOf(word)!=-1;
	}
}
